package com.example.springbootblog.common.advice;

import com.example.springbootblog.common.exception.BlogException;
import com.example.springbootblog.common.pojo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * 统一异常处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionAdvice {

    //    父类异常
    @ExceptionHandler(Exception.class)
    public Result handler(Exception e) {
        log.info("父类异常");
        return Result.fail(e.getMessage());
    }

    //    空指针异常
    @ExceptionHandler(NullPointerException.class)
    public Result blogNullPointerException(Exception e) {
        log.info("空指针异常");
        return Result.fail(e.getMessage());
    }

    //    自定义异常
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ExceptionHandler(BlogException.class)
    public Result blogException(Exception e) {
        log.info(e.getMessage());
        return Result.fail(e.getMessage(),HttpStatus.BAD_GATEWAY.value());
    }

    // 文件资源异常
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoResourceFoundException.class)
    public Result blogNoResourceFoundException(Exception e) {
        log.info("文件资源异常");
        return Result.fail(e.getMessage(),HttpStatus.NOT_FOUND.value());
    }


    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    //    参数校验异常
    @ExceptionHandler({HandlerMethodValidationException.class, MethodArgumentNotValidException.class})
    public Result blogArgException(Exception e) {
        log.info("参数校验异常");
        return Result.fail(e.getMessage(),HttpStatus.NOT_ACCEPTABLE.value());
    }

}
